package com.pap.rbac.role.agent.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pap.base.service.impl.PapBaseServiceImpl;
import com.pap.base.util.date.DateUtils;
import com.pap.base.util.string.StringUtilss;
import com.pap.obj.vo.response.ResponseVO;
import com.pap.rbac.agent.role.IRoleAgent;
import com.pap.rbac.agent.role.dto.RoleTreeNodeVO;
import com.pap.rbac.role.auto.entity.Role;
import com.pap.rbac.role.auto.mapper.RoleMapper;

@Transactional
@Service("roleAgent")
public class RoleAgentImpl extends PapBaseServiceImpl<Role> implements IRoleAgent {

	@Autowired
	private RoleMapper roleMapper;
	

	@Override
	public List<RoleTreeNodeVO> roleTreeJson(String clientLicenseId, String globalParentId) {
		return roleMapper.roleTreeJson(clientLicenseId, globalParentId);
	}

	@Override
	public ResponseVO<Role> updateAndCheckRole(Role inputRole, String loginUserId) {
		// 检验是否循环依赖
		if(checkTreeCircularDependency(inputRole.getId(), inputRole.getParentId())) {
			// 更新当前的角色
			inputRole.setModifyIp("0.0.0.0");
			inputRole.setModifyTime(DateUtils.getCurrDateTimeStr());
			inputRole.setModifyUser(loginUserId);
			
			roleMapper.updateByPrimaryKeySelective(inputRole);
			
			if("-1".equals(inputRole.getParentId())) {
				Role tempForPath = roleMapper.selectByPrimaryKey(inputRole.getId());
				tempForPath.setPathCodes(null);
				tempForPath.setPathIds(null);
				tempForPath.setPathNames(null);
				tempForPath.setLevel("0");
				roleMapper.updateByPrimaryKey(tempForPath);
			} else {
				Role tempForPath = roleMapper.selectByPrimaryKey(inputRole.getId());
				Role tempParentForPath = roleMapper.selectByPrimaryKey(inputRole.getParentId());
				if(StringUtilss.isNotEmpty(tempParentForPath.getPathIds())) {
					tempForPath.setPathIds(tempParentForPath.getPathIds() + "," + tempParentForPath.getId());
        		} else {
        			tempForPath.setPathIds(tempParentForPath.getId());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathCodes())) {
        			tempForPath.setPathCodes(tempParentForPath.getPathCodes() + "," + tempParentForPath.getCode());
        		} else {
        			tempForPath.setPathCodes(tempParentForPath.getCode());
        		}
        		if(StringUtilss.isNotEmpty(tempParentForPath.getPathNames())) {
        			tempForPath.setPathNames(tempParentForPath.getPathNames() + "," + tempParentForPath.getName());
        		} else {
        			tempForPath.setPathNames(tempParentForPath.getName());
        		}
				// level
				if(StringUtilss.isNotEmpty(tempParentForPath.getLevel())) {
					tempForPath.setLevel((Integer.parseInt(tempParentForPath.getLevel()) + 1) + "");
				} else {
					tempForPath.setLevel("0");
				}
        		roleMapper.updateByPrimaryKey(tempForPath);
			}
			
			// 维护子集的角色
			ResponseVO<Role> responseVO =  updateRecursionPathColumnRole(inputRole.getId());
			return responseVO;
		} else {
			return ResponseVO.validfail("角色被循环依赖，请检查数据有效性!");
		}
	}
	
	/**
	 * 新维护的角色，是否被循环依赖的校验
	 * @param operaRoleId
	 * @param newParentRoleId
	 * @return
	 */
	@Override
    public Boolean checkTreeCircularDependency(String operaRoleId, String newParentRoleId) {
    	String parentRoleTemp = "";
    	Role newParentRoleInfo = roleMapper.selectByPrimaryKey(newParentRoleId);
    	if(newParentRoleInfo != null) {
    		if(StringUtilss.isNotEmpty(newParentRoleInfo.getPathIds())) {
    			parentRoleTemp = newParentRoleInfo.getPathIds() + ",";
    		}
    		parentRoleTemp += newParentRoleInfo.getId();
    	}
    	if (StringUtilss.checkArrayValue(parentRoleTemp.split(","), operaRoleId)) {
    		return false;
    	} else {
    		return true;
    	}
    }

	@Override
	public ResponseVO<Role> updateRecursionPathColumnRole(String inputRoleId) {
		try {  
			Map<Object, Object> parentIdMap = new HashMap<Object, Object>();
			parentIdMap.put("parentId", inputRoleId);
            List<Role> list = roleMapper.selectListByMap(parentIdMap);
            if (null != list && list.size()>0) {  
                for (int i = 0; i < list.size(); i++) {  
                	Role role = list.get(i);  
                	// 更新数据
                	Role parentTemp = roleMapper.selectByPrimaryKey(role.getParentId());
                	if(parentTemp != null) {
                		if(StringUtilss.isNotEmpty(parentTemp.getPathIds())) {
                			role.setPathIds(parentTemp.getPathIds() + "," + parentTemp.getId());
                		} else {
                			role.setPathIds(parentTemp.getId());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathCodes())) {
                			role.setPathCodes(parentTemp.getPathCodes() + "," + parentTemp.getCode());
                		} else {
                			role.setPathCodes(parentTemp.getCode());
                		}
                		if(StringUtilss.isNotEmpty(parentTemp.getPathNames())) {
                			role.setPathNames(parentTemp.getPathNames() + "," + parentTemp.getName());
                		} else {
                			role.setPathNames(parentTemp.getName());
                		}
        				// level
        				if(StringUtilss.isNotEmpty(parentTemp.getLevel())) {
        					role.setLevel((Integer.parseInt(parentTemp.getLevel()) + 1) + "");
        				} else {
        					role.setLevel("0");
        				}
                	} else {
                		role.setPathCodes(null);
                		role.setPathIds(null);
                		role.setPathNames(null);
                	}
                	roleMapper.updateByPrimaryKey(role);
                	updateRecursionPathColumnRole(role.getId());  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
            return ResponseVO.validfail(e.getMessage());
        }  
		return ResponseVO.successdata("更新成功");
	}
}
